package com._5704.website.shiro;

import com._5704.website.entity.User;
import com._5704.website.service.ServiceImpl.UserServiceImpl;
import com._5704.website.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

//@Component
public class MyRealm extends AuthorizingRealm {

    @Resource
    @Lazy
    private UserServiceImpl userService;

    /**
     * 根据token判断此Authenticator是否使用该realm
     * 必须重写不然shiro会报错
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 获取授权信息
     * @param principal doGetAuthenticationInfo 传过来的
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        System.out.println("-----------授权-----------");
        String token = (String) principal.getPrimaryPrincipal();
        String id = JwtUtil.getUserId(token);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = userService.getUser(id);
        if (userService.isAdmin(user)){
            info.addRole("admin");
            info.addRole("insider");
            info.addRole("user");
        }else if (userService.isInsider(user)){
            info.addRole("insider");
            info.addRole("user");
        }else if (userService.isBalckLister(user)){
            info.addRole("noUser");
        }else{
            info.addRole("user");
        }

        return info;
    }

    /**
     * 获取登录信息
     * @param token token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
        System.out.println("-----------认证-----------");
        String jwt= (String) token.getCredentials();

        if (!JwtUtil.verify(jwt)){
            throw new AuthenticationException();
        }
        String id = JwtUtil.getUserId(jwt);

        User user = userService.getUser(id);

        System.out.println("userId:" + user.getUserId());
        System.out.println("userPerms:" + user.getPerms());

        return new SimpleAuthenticationInfo(jwt,jwt,"MyRealm");
    }
}
